package com.maiji.cloud.listener;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.maiji.cloud.entities.login.ArticleCommentEntity;
import com.maiji.cloud.entities.login.UploadRecord;
import com.maiji.cloud.service.ArticleCommentService;
import com.maiji.cloud.service.UploadRecordService;
import com.maiji.cloud.utils.BaiduAI;
import com.maiji.cloud.utils.MaijiOSS;
import com.maiji.cloud.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.ReduceWeightFundLogEntity;
import com.maiji.cloud.mapper.AppUserMapper;
import com.maiji.cloud.mapper.ReduceWeightFundLogMapper;
import com.maiji.cloud.mapper.ShareWeightHelpUserLogMapper;
import com.maiji.cloud.request.shopingmall.DistributeFundReqDto;
import com.maiji.cloud.request.shopingmall.DistributeFundReqDto.DistributeFundReqData;
import com.maiji.cloud.service.shopping.IntegralService;
import com.maiji.cloud.utils.FlowTypeEnum;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ScheduledService {

	Logger logger = LoggerFactory.getLogger(ScheduledService.class);
    @Autowired
    private RedisTemplate<String, Object> maiji1RedisTemplate;
    @Autowired
    private RedisTemplate<String, Object> maiji2RedisTemplate;
	@Autowired
	private IntegralService integralService;
	@Autowired
	private ShareWeightHelpUserLogMapper shareWeightHelpUserLogMapper;
	@Autowired
	private AppUserMapper appUserMapper;
	@Autowired
	private ReduceWeightFundLogMapper reduceWeightFundLogMapper;
    @Autowired
    private UploadRecordService uploadRecordService;
    @Autowired
    private ArticleCommentService articleCommentService;

	/**
	 * 定时统计分享体重助力减肥基金
     * 每个整点时间执行一次
	 */
	 @Scheduled(cron = "${cron.settle}")
	public void settle() {
		List<ReduceWeightFundLogEntity> list = reduceWeightFundLogMapper.getReduceWeightFundLogEntityList(new Date());
		for(ReduceWeightFundLogEntity reduceWeightFundLogEntity : list) {
			Double sumFund = shareWeightHelpUserLogMapper.getSumFund(reduceWeightFundLogEntity.getUuId());
			DistributeFundReqDto distributeFundReqDto = new DistributeFundReqDto();
			DistributeFundReqData distributeFundReqData = distributeFundReqDto.dataInstance();
			distributeFundReqData.setFund(sumFund);
			distributeFundReqData.setRelevantId(reduceWeightFundLogEntity.getUuId());
			distributeFundReqData.setRemark(FlowTypeEnum.HELP_LOSE_WEIGHT_FUND);
			distributeFundReqDto.setData(distributeFundReqData);
			AppUser appUser = appUserMapper.selectById(reduceWeightFundLogEntity.getUserId());
			Boolean bool = null;
			if (sumFund != null) {
                String token = appUser.getToken();
                RedisUtil.setObject(maiji1RedisTemplate, "maijiToken:" + token, appUser);
                if (maiji2RedisTemplate != null) RedisUtil.setObject(maiji2RedisTemplate, "maijiToken:" + token, appUser);
				bool = integralService.distributeFundByToken(distributeFundReqDto, token);
				logger.info("用户{}分享体重记录id 为  {} 助力结束，结算结果 is {}", reduceWeightFundLogEntity.getUserId(),
						reduceWeightFundLogEntity.getUuId(), bool);
			} 
			if (bool != null && !bool)
				continue;
			reduceWeightFundLogEntity.setSettlement(1);
			reduceWeightFundLogMapper.updateById(reduceWeightFundLogEntity);
			logger.info("用户{}分享体重记录id 为  {} 助力结束，结算金额 is {}", reduceWeightFundLogEntity.getUserId(),
					reduceWeightFundLogEntity.getUuId(), sumFund);
		}
	}

    /**
     * 定时清理阿里云OSS垃圾文件
     * 每日3点执行一次
     */
    @Scheduled(cron = "${cron.clearOSS}")
    public void clearOSS () {
        EntityWrapper<UploadRecord> entityWrapper = new EntityWrapper<>();
        entityWrapper.isNull("belong_id");
        entityWrapper.isNotNull("bucket_name");
        List<UploadRecord> uploadRecords = uploadRecordService.selectList(entityWrapper);
        Map<String, List<UploadRecord>> upsMap = uploadRecords.parallelStream().collect(Collectors.groupingBy(UploadRecord::getBucketName));
        Map<String, List<String>> map = Maps.newHashMap();
        for (String key: upsMap.keySet()) map.put(key, upsMap.get(key).parallelStream().map(UploadRecord::getFileName).collect(Collectors.toList()));
        if (map.size() > 0) if (! MaijiOSS.aliyunOSSBatchDel2(map)) return;
        List<String> urIds = uploadRecords.parallelStream().map(UploadRecord::getUuId).collect(Collectors.toList());
        if (uploadRecordService.deleteBatchIds(urIds))
            logger.info("定时清理阿里云OSS垃圾文件{}个 ===>> 成功 [ belong_id = null, bucket_name != null ]", urIds.size());
    }

    // 定时审核文章评论内容
    /*@Scheduled(cron = "${cron.examineArticleComment}")
    public void examineArticleComment () {
        EntityWrapper<ArticleCommentEntity> entityWrapper = new EntityWrapper<>();
        entityWrapper.isNull("operation_id");
        List<ArticleCommentEntity> articleComments = articleCommentService.selectList(entityWrapper);
        articleComments = articleComments.stream().map(ac -> {
            try {
                Thread.sleep(222);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (! BaiduAI.examineText(ac.getContent())) return ac.setIsDel(1);
            return ac.setOperationId("123456").setOperationName("自动审核");
        }).collect(Collectors.toList());
        String updateBatchById = articleCommentService.updateBatchById(articleComments) ? "成功" : "失败";
        logger.info("定时审核动态评论 ===>> {} ===>> msgCommentIds = {}", updateBatchById, articleComments
                .parallelStream().map(ArticleCommentEntity::getUuId).collect(Collectors.toList()));
    }*/

}
